<?php //echo 'Hi, Infant'; exit;
	// config and whatnot
	session_start();
    $config = dirname(__FILE__) . '/../config.php';
    require_once( "../Hybrid/Auth.php" );

	$user_data = NULL;
	// try to get the user profile from an authenticated provider
	try{
		$hybridauth = new Hybrid_Auth( $config );

		// selected provider name 
		$provider = @ trim( strip_tags( $_GET["provider"] ) );

		// check if the user is currently connected to the selected provider
		if( !  $hybridauth->isConnectedWith( $provider ) ){ 
			// redirect him back to login page
			header( "Location: login.php?error=Your are not connected to $provider or your session has expired" );
		}

		// call back the requested provider adapter instance (no need to use authenticate() as we already did on login page)
		$adapter = $hybridauth->getAdapter( $provider );

		// grab the user profile
		$user_data = $adapter->getUserProfile();
		
		//echo '<pre>';
		//print_r($user_data); exit;
				
		get_mysql_connection();
				
		$authentication_info = find_by_provider_uid( $provider, $user_data->identifier );
		
		$logout = '<a href="javascript:;" route="logout" id="social_logout">Facebook Logout</a>';
		
		if( $authentication_info ){
			// 2.1 - store last created fb user_id in session
			/*
			echo '<pre>';			
			print_r($authentication_info);  exit;
			*/
			
			$resData = array();
			
			$sql = "SELECT * FROM client_social_applicationcontact WHERE social_user_id = ".$authentication_info["id"]." ORDER BY id DESC LIMIT 1";
		
		/*echo $sql;
		$sqlRes = mysql_query($sql);			
		echo '<pre>';
		$resData = mysql_fetch_assoc($sqlRes);
		print_r($resData); 			
		exit;*/
			
			if(!$sqlRes = mysql_query($sql)){
				$_SESSION["fb_user_id"] = $authentication_info["id"]; 
				$_SESSION['fb_email'] = $authentication_info["email"]; 
				//window.opener.document.getElementById("social").appendChild = "'.$logout.'";
				//header( "Location:http://www.maxcash.com.au/apply-now.php" );
				die('<script>alert("your basic details already exist, please fulfill the form and submit");
								   //alert(window.opener.document.getElementById("fbconnect").text);
								   window.close();	
								   window.opener.document.getElementById("social_logout").setAttribute("style", "display:block;");
								   window.opener.document.getElementById("fbconnect").setAttribute("data", "disabled");
								   window.opener.document.getElementById("fbconnect").setAttribute("style", "cursor:not-allowed; display:none;");
								   </script>');
			} 
			else
			{
				if(mysql_num_rows($sqlRes) > 0)
				{
					$resData = mysql_fetch_assoc($sqlRes);
				}
			}
			
			
			if(isset($resData['app_id']) && $resData['app_id'])
			{
				
				
				//echo '<pre>'; print_r($resData); exit;
			
				$_SESSION['display_name'] = $authentication_info['display_name'];
				$_SESSION['app_email_addr'] = $authentication_info['email'];
				$_SESSION['applicant_id'] = $resData['Contact_ID'];
				$_SESSION['CurrentContact_id'] = $resData['Contact_ID'];			
				$_SESSION['app_id'] = $resData['app_id'];
				$_SESSION["fb_user_id"] = '';
				//header( "Location:http://www.maxcash.com.au/account/index.php?dashboard" );
				die('<script>alert("You have successfully logged in");
								   window.close();
								   window.opener.location = "http://www.maxcash.com.au/account/index.php?dashboard";
								   </script>');
			}
			else
			{
				$_SESSION["fb_user_id"] = $authentication_info["id"]; 
				//header( "Location:http://www.maxcash.com.au/apply-now.php" );
				//window.opener.document.getElementById("EMailAddress1").value = "'.$authentication_info["email"].'"
				$_SESSION['fb_email'] = $authentication_info["email"]; 
				die('<script>alert("your basic details already exist, please fulfill the form and submit");
								   window.close();	
								   window.opener.document.getElementById("social_logout").setAttribute("style", "display:block;");
								   window.opener.document.getElementById("fbconnect").setAttribute("data", "disabled");
								   window.opener.document.getElementById("fbconnect").setAttribute("style", "cursor:not-allowed; display:none;");
								   </script>');
			}
			
			
			
			// 2.2 - redirect to user/profile
			//$this->redirect( "users/profile" );
		}
		
		/*
		if( $user_data->email ){
			$user_info = find_by_email( $user_data->email ); 

			if( $user_info ) {
				die( '<br /><b style="color:red">Well! the email returned by the provider ('. $user_data->email .') already exist in our database, so in this case you might use the <a href="index.php?route=users/login">Sign-in</a> to login using your email and password.</b>' );
			}
		}
		*/ 
		
		# 4 - if authentication does not exist and email is not in use, then we create a new user 
		$provider_uid  = $user_data->identifier;
		$email         = $user_data->email;
		$first_name    = $user_data->firstName;
		$last_name     = $user_data->lastName;
		$display_name  = $user_data->displayName;
		$website_url   = $user_data->webSiteURL;
		$profile_url   = $user_data->profileURL;
		$password      = rand( ) ; # for the password we generate something random

		// 4.1 - create new user
		//$new_user_id = $user->create( $email, $password, $first_name, $last_name ); 
		
		// 4.2 - creat a new authentication for him
		$fb_user_id = create_new_facebook_user( $provider, $provider_uid, $email, $display_name, $first_name, $last_name, $profile_url, $website_url );

		// 4.3 - store the new user_id in session
		$_SESSION["fb_user_id"] = $fb_user_id;
		$_SESSION['fb_email'] = $email;

		// 4.4 - redirect to user/profile
		//$this->redirect( "users/profile" );
		//header( "Location:http://www.maxcash.com.au/apply-now.php" );
		//window.opener.document.getElementById("EMailAddress1").value = "'.$email.'"
		die('<script>
			alert("your basic details has been saved, please fulfill the form and submit");
			window.close();			
			window.opener.document.getElementById("social_logout").setAttribute("style", "display:block;");
			window.opener.document.getElementById("fbconnect").setAttribute("data", "disabled");		
			window.opener.document.getElementById("fbconnect").setAttribute("style", "cursor:not-allowed; display:none;");
			</script>');
		
    }
	catch( Exception $e ){  
		// In case we have errors 6 or 7, then we have to use Hybrid_Provider_Adapter::logout() to 
		// let hybridauth forget all about the user so we can try to authenticate again.

		// Display the recived error, 
		// to know more please refer to Exceptions handling section on the userguide
		switch( $e->getCode() ){ 
			case 0 : echo "Unspecified error."; break;
			case 1 : echo "Hybriauth configuration error."; break;
			case 2 : echo "Provider not properly configured."; break;
			case 3 : echo "Unknown or disabled provider."; break;
			case 4 : echo "Missing provider application credentials."; break;
			case 5 : echo "Authentication failed. " 
					  . "The user has canceled the authentication or the provider refused the connection."; 
			case 6 : echo "User profile request failed. Most likely the user is not connected "
					  . "to the provider and he should to authenticate again."; 
				   $adapter->logout(); 
				   break;
			case 7 : echo "User not connected to the provider."; 
				   $adapter->logout(); 
				   break;
		} 

		echo "<br /><br /><b>Original error message:</b> " . $e->getMessage();

		echo "<hr /><h3>Trace</h3> <pre>" . $e->getTraceAsString() . "</pre>";  
	}
	
	//mysql connection
	
	function get_mysql_connection()
	{
		$database_host = "localhost"; 
		$database_user = "root";
		$database_pass = "";
		$database_name = "morganse_crm";
		
	
		$database_link = @ mysql_connect( $database_host, $database_user, $database_pass );
	
		if ( ! $database_link ) {
			die( "This sample requires a Mysql database. Please edit the configuration file: <b>application.config.php</b>. <hr><b>Mysql error</b>: " . mysql_error() );
		}
	
		$db_selected = mysql_select_db( $database_name, $database_link );
	
		if ( ! $db_selected ) {
			die( "This sample requires a Mysql database. Please edit the configuration file: <b>application.config.php</b>. <hr><b>Mysql error</b>: " . mysql_error() );
		}
	}
	
	function mysql_query_excute( $sql ){ 
		$result = mysql_query($sql);
 
		if (!$result) {
			$message  = 'Invalid query: ' . mysql_error() . "\n";
			$message .= 'Whole query: ' . $sql;
			die($message);
		}

		return $result;
	}
	
	
	// authentication model functions
	
	function find_by_provider_uid( $provider, $provider_uid ){
		$sql = "SELECT * FROM client_social_authentications WHERE provider = '".strtolower($provider)."' AND provider_uid = '$provider_uid' LIMIT 1";
		
		$result = mysql_query_excute($sql);

		return mysql_fetch_assoc($result);
	}

	function create_new_facebook_user( $provider, $provider_uid, $email, $display_name, $first_name, $last_name, $profile_url, $website_url ){ 
		$sql = "INSERT INTO client_social_authentications ( id, provider, provider_uid, email, display_name, first_name, last_name, profile_url, website_url, created_at ) VALUES ( '', '$provider', '$provider_uid', '$email', '$display_name', '$first_name', '$last_name', '$profile_url', '$website_url', NOW() ) ";

		mysql_query_excute($sql);

		return mysql_insert_id();
	} 
	
	function find_by_user_id( $OriginalContact_id ){ 
		$sql = "SELECT * FROM client_social_authentications WHERE id = '$social_user_id' LIMIT 1";

		$result = mysql_query_excute($sql);
 
		return mysql_fetch_assoc($result);
	} 
	
	// users model function
	
	function find_by_id( $id ){
		//$sql = "SELECT * FROM users WHERE id = '$id' LIMIT 1";
		$sql = "SELECT * FROM crm_contact WHERE id = '$id' LIMIT 1";
		$result = mysql_query_excute($sql);

		return mysql_fetch_assoc($result);
	}

	function find_by_email( $email ){
		//$sql = "SELECT * FROM crm_contact WHERE Email = '$email' LIMIT 1";
		$sql = "SELECT * FROM crm_contact WHERE Email = '$email' LIMIT 1";
		$result = mysql_query_excute($sql);
 
		return mysql_fetch_assoc($result);
	}
	
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en">
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="public/css.css" type="text/css">
</head>
<body>  
<?php
	if( $user_data ){
?> 
<table width="90%" border="0" cellpadding="2" cellspacing="2">
  <tr>
    <td valign="top">
		<?php
			include "includes/menu.php";
		?> 
		<fieldset>
        <legend>Profile information</legend>
        <table width="100%">
          <tr>
            <td width="150" valign="top" align="center">
				<?php
					if( $user_data->photoURL ){
				?>
					<a href="<?php echo $user_data->profileURL; ?>"><img src="<?php echo $user_data->photoURL; ?>" title="<?php echo $user_data->displayName; ?>" border="0" width="100" height="120"></a>
				<?php
					}
					else{
				?> 
				<img src="public/avatar.png" title="<?php echo $user_data->displayName; ?>" border="0" >
				<?php
					} 
				?>  
			</td>
            <td align="left"><table width="100%" cellspacing="0" cellpadding="3" border="0">
                <tbody>
                  <tr>
                    <td width="10%">providerID</td>
                    <td width="83%">&nbsp; <?php echo $adapter->id; ?></td>
                  </tr>
                  <tr>
                    <td width="10%">identifier</td>
                    <td width="83%">&nbsp; <?php echo $user_data->identifier; ?></td>
                  </tr> 
                  <tr>
                    <td>profileURL</td>
                    <td>&nbsp; <a href="<?php echo $user_data->profileURL; ?>"><?php echo $user_data->profileURL; ?></a></td>
                  </tr>
                  <tr>
                    <td>webSiteURL</td>
                    <td>&nbsp; <?php echo $user_data->webSiteURL; ?></td>
                  </tr>
                  <tr>
                    <td>photoURL</td>
                    <td>&nbsp; <?php echo $user_data->photoURL; ?></td>
                  </tr>
                  <tr>
                    <td>displayName</td>
                    <td>&nbsp; <?php echo $user_data->displayName; ?></td>
                  </tr>
                  <tr>
                    <td>description</td>
                    <td>&nbsp; <?php echo $user_data->description; ?></td>
                  </tr>
                  <tr>
                    <td>firstName</td>
                    <td>&nbsp; <?php echo $user_data->firstName; ?></td>
                  </tr>
                  <tr>
                    <td>lastName</td>
                    <td>&nbsp; <?php echo $user_data->lastName; ?></td>
                  </tr>
                  <tr>
                    <td>gender</td>
                    <td>&nbsp; <?php echo $user_data->gender; ?></td>
                  </tr>
                  <tr>
                    <td>language</td>
                    <td>&nbsp; <?php echo $user_data->language; ?></td>
                  </tr>
                  <tr>
                    <td>age</td>
                    <td>&nbsp; <?php echo $user_data->age; ?></td>
                  </tr>
                  <tr>
                    <td>birthDay</td>
                    <td>&nbsp; <?php echo $user_data->birthDay; ?></td>
                  </tr>
                  <tr>
                    <td>birthMonth</td>
                    <td>&nbsp; <?php echo $user_data->birthMonth; ?></td>
                  </tr>
                  <tr>
                    <td>birthYear</td>
                    <td>&nbsp; <?php echo $user_data->birthYear; ?></td>
                  </tr>
                  <tr>
                    <td>email</td>
                    <td>&nbsp; <?php echo $user_data->email; ?></td>
                  </tr>
                  <tr>
                    <td>phone</td>
                    <td>&nbsp; <?php echo $user_data->phone; ?></td>
                  </tr>
                  <tr>
                    <td>address</td>
                    <td>&nbsp; <?php echo $user_data->address; ?></td>
                  </tr>
                  <tr>
                    <td>country</td>
                    <td>&nbsp; <?php echo $user_data->country; ?></td>
                  </tr>
                  <tr>
                    <td>region</td>
                    <td>&nbsp; <?php echo $user_data->region; ?></td>
                  </tr>
                  <tr>
                    <td>city</td>
                    <td>&nbsp; <?php echo $user_data->city; ?></td>
                  </tr>
                  <tr>
                    <td>zip</td>
                    <td>&nbsp; <?php echo $user_data->zip; ?></td>
                  </tr>
                </tbody>
              </table> 
			  </td>
          </tr>  
        </table>
		</fieldset>
	</td>
    <td valign="top" width="250" align="left"> 
		<?php
			include "includes/sidebar.php";
		?>
	</td>
  </tr>
</table>  
<?php
	} // if( $user_data )

	include "includes/debugger.php";
?> 
</body>
</html>
